package com.smart.community.payment.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.payment.dto.PaymentDTO;
import com.smart.community.payment.entity.Payment;
import com.smart.community.payment.service.IPaymentService;
import com.smart.community.payment.vo.PaymentVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 支付管理控制器
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2025-06-26
 */
@Slf4j
@RestController
@RequestMapping("/api/payment")
@Tag(name = "支付管理", description = "支付订单管理、支付状态处理、退款管理等接口")
@SaCheckLogin
@Validated
public class PaymentController {

    @Autowired
    private IPaymentService paymentService;

    // ========================= 支付订单管理接口 =========================

    /**
     * 创建支付订单
     * 
     * @param paymentDTO 支付信息
     * @return 支付订单
     */
    @PostMapping("/create")
    @Operation(summary = "创建支付订单", description = "创建新的支付订单")
    public Result<Payment> createPayment(@Valid @RequestBody PaymentDTO paymentDTO) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("创建支付订单，用户ID: {}, 金额: {}, 支付方式: {}", 
                currentUserId, paymentDTO.getAmount(), paymentDTO.getPaymentMethod());
            
            // 验证支付参数
            if (!paymentDTO.validatePayment()) {
                return Result.fail("支付参数验证失败");
            }
            
            Payment payment = paymentService.createPayment(paymentDTO);
            log.info("创建支付订单成功，订单号: {}", payment.getOrderNo());
            return Result.success("创建成功", payment);
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            return Result.fail("创建失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询支付记录
     * 
     * @param paymentDTO 查询条件
     * @return 分页结果
     */
    @PostMapping("/page")
    @Operation(summary = "分页查询支付记录", description = "支持按用户、社区、状态等条件查询")
    public Result<PageResult<PaymentVO>> pagePayments(@Valid @RequestBody PaymentDTO paymentDTO) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("分页查询支付记录，用户ID: {}, 社区ID: {}, 当前页: {}, 每页大小: {}", 
                currentUserId, paymentDTO.getCommunityId(), paymentDTO.getCurrent(), paymentDTO.getSize());
            
            PageResult<PaymentVO> result = paymentService.pagePayments(paymentDTO);
            log.info("分页查询支付记录成功，总记录数: {}", result.getTotal());
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("分页查询支付记录失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询支付详情
     * 
     * @param id 支付ID
     * @return 支付详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询支付详情", description = "根据ID查询支付详情")
    public Result<PaymentVO> getPaymentDetail(
            @Parameter(description = "支付ID") @PathVariable @NotNull Long id) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("查询支付详情，支付ID: {}, 用户ID: {}", id, currentUserId);
            
            PaymentVO paymentVO = paymentService.getPaymentDetail(id);
            if (paymentVO == null) {
                return Result.fail("支付记录不存在");
            }
            
            log.info("查询支付详情成功，订单号: {}", paymentVO.getOrderNo());
            return Result.success("查询成功", paymentVO);
        } catch (Exception e) {
            log.error("查询支付详情失败，支付ID: {}", id, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据订单号查询支付详情
     * 
     * @param orderNo 订单号
     * @return 支付详情
     */
    @GetMapping("/order/{orderNo}")
    @Operation(summary = "根据订单号查询支付详情", description = "根据订单号查询支付详情")
    public Result<PaymentVO> getPaymentByOrderNo(
            @Parameter(description = "订单号") @PathVariable @NotNull String orderNo) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("根据订单号查询支付详情，订单号: {}, 用户ID: {}", orderNo, currentUserId);
            
            PaymentVO paymentVO = paymentService.getPaymentByOrderNo(orderNo);
            if (paymentVO == null) {
                return Result.fail("支付记录不存在");
            }
            
            log.info("根据订单号查询支付详情成功，订单号: {}", orderNo);
            return Result.success("查询成功", paymentVO);
        } catch (Exception e) {
            log.error("根据订单号查询支付详情失败，订单号: {}", orderNo, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户ID查询支付记录
     * 
     * @param userId 用户ID
     * @return 支付记录列表
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "根据用户ID查询支付记录", description = "查询指定用户的所有支付记录")
    public Result<List<PaymentVO>> getPaymentsByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotNull Long userId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("根据用户ID查询支付记录，用户ID: {}, 当前用户ID: {}", userId, currentUserId);
            
            List<PaymentVO> payments = paymentService.getPaymentsByUserId(userId);
            log.info("根据用户ID查询支付记录成功，记录数: {}", payments.size());
            return Result.success("查询成功", payments);
        } catch (Exception e) {
            log.error("根据用户ID查询支付记录失败，用户ID: {}", userId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据社区ID查询支付记录
     * 
     * @param communityId 社区ID
     * @return 支付记录列表
     */
    @GetMapping("/community/{communityId}")
    @Operation(summary = "根据社区ID查询支付记录", description = "查询指定社区的所有支付记录")
    public Result<List<PaymentVO>> getPaymentsByCommunityId(
            @Parameter(description = "社区ID") @PathVariable @NotNull Long communityId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("根据社区ID查询支付记录，社区ID: {}, 用户ID: {}", communityId, currentUserId);
            
            List<PaymentVO> payments = paymentService.getPaymentsByCommunityId(communityId);
            log.info("根据社区ID查询支付记录成功，记录数: {}", payments.size());
            return Result.success("查询成功", payments);
        } catch (Exception e) {
            log.error("根据社区ID查询支付记录失败，社区ID: {}", communityId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    // ========================= 支付状态处理接口 =========================

    /**
     * 更新支付状态
     * 
     * @param id 支付ID
     * @param paymentStatus 支付状态
     * @return 更新结果
     */
    @PutMapping("/{id}/status")
    @Operation(summary = "更新支付状态", description = "更新支付订单的状态")
    public Result<Boolean> updatePaymentStatus(
            @Parameter(description = "支付ID") @PathVariable @NotNull Long id,
            @Parameter(description = "支付状态：0-待支付，1-支付中，2-支付成功，3-支付失败，4-已退款") 
            @RequestParam @NotNull Integer paymentStatus) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("更新支付状态，支付ID: {}, 状态: {}, 用户ID: {}", id, paymentStatus, currentUserId);
            
            boolean success = paymentService.updatePaymentStatus(id, paymentStatus);
            if (success) {
                log.info("更新支付状态成功，支付ID: {}", id);
                return Result.success("更新成功", true);
            } else {
                return Result.fail("更新失败，支付记录不存在或无权限");
            }
        } catch (Exception e) {
            log.error("更新支付状态失败，支付ID: {}", id, e);
            return Result.fail("更新失败：" + e.getMessage());
        }
    }

    /**
     * 取消支付订单
     * 
     * @param id 支付ID
     * @param reason 取消原因
     * @return 取消结果
     */
    @PutMapping("/{id}/cancel")
    @Operation(summary = "取消支付订单", description = "取消支付订单")
    public Result<Boolean> cancelPayment(
            @Parameter(description = "支付ID") @PathVariable @NotNull Long id,
            @Parameter(description = "取消原因") @RequestParam @NotNull String reason) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("取消支付订单，支付ID: {}, 取消原因: {}, 用户ID: {}", id, reason, currentUserId);
            
            boolean success = paymentService.cancelPayment(id, reason);
            if (success) {
                log.info("取消支付订单成功，支付ID: {}", id);
                return Result.success("取消成功", true);
            } else {
                return Result.fail("取消失败，支付记录不存在或无权限");
            }
        } catch (Exception e) {
            log.error("取消支付订单失败，支付ID: {}", id, e);
            return Result.fail("取消失败：" + e.getMessage());
        }
    }

    /**
     * 重新支付
     * 
     * @param id 支付ID
     * @param paymentMethod 支付方式
     * @return 重新支付结果
     */
    @PostMapping("/{id}/repay")
    @Operation(summary = "重新支付", description = "重新支付失败的订单")
    public Result<PaymentVO> repayPayment(
            @Parameter(description = "支付ID") @PathVariable @NotNull Long id,
            @Parameter(description = "支付方式：1-微信支付，2-支付宝，3-银行卡，4-现金") 
            @RequestParam @NotNull Integer paymentMethod) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("重新支付，支付ID: {}, 支付方式: {}, 用户ID: {}", id, paymentMethod, currentUserId);
            
            PaymentVO paymentVO = paymentService.repayPayment(id, paymentMethod);
            if (paymentVO == null) {
                return Result.fail("重新支付失败，支付记录不存在或无权限");
            }
            
            log.info("重新支付成功，订单号: {}", paymentVO.getOrderNo());
            return Result.success("重新支付成功", paymentVO);
        } catch (Exception e) {
            log.error("重新支付失败，支付ID: {}", id, e);
            return Result.fail("重新支付失败：" + e.getMessage());
        }
    }

    // ========================= 支付回调处理接口 =========================

    /**
     * 处理支付成功回调
     * 
     * @param orderNo 订单号
     * @param thirdPartyOrderNo 第三方订单号
     * @param channelCode 支付渠道编码
     * @return 处理结果
     */
    @PostMapping("/success")
    @Operation(summary = "处理支付成功回调", description = "处理第三方支付成功回调")
    public Result<Boolean> handlePaymentSuccess(
            @Parameter(description = "订单号") @RequestParam @NotNull String orderNo,
            @Parameter(description = "第三方订单号") @RequestParam @NotNull String thirdPartyOrderNo,
            @Parameter(description = "支付渠道编码") @RequestParam @NotNull String channelCode) {
        try {
            log.info("处理支付成功回调，订单号: {}, 第三方订单号: {}", orderNo, thirdPartyOrderNo);
            
            boolean success = paymentService.handlePaymentSuccess(orderNo, thirdPartyOrderNo, channelCode);
            if (success) {
                log.info("处理支付成功回调成功，订单号: {}", orderNo);
                return Result.success("处理成功", true);
            } else {
                return Result.fail("处理失败，订单不存在或状态异常");
            }
        } catch (Exception e) {
            log.error("处理支付成功回调失败，订单号: {}", orderNo, e);
            return Result.fail("处理失败：" + e.getMessage());
        }
    }

    /**
     * 处理支付失败回调
     * 
     * @param orderNo 订单号
     * @param failureReason 失败原因
     * @return 处理结果
     */
    @PostMapping("/failure")
    @Operation(summary = "处理支付失败回调", description = "处理第三方支付失败回调")
    public Result<Boolean> handlePaymentFailure(
            @Parameter(description = "订单号") @RequestParam @NotNull String orderNo,
            @Parameter(description = "失败原因") @RequestParam @NotNull String failureReason) {
        try {
            log.info("处理支付失败回调，订单号: {}, 失败原因: {}", orderNo, failureReason);
            
            boolean success = paymentService.handlePaymentFailure(orderNo, failureReason);
            if (success) {
                log.info("处理支付失败回调成功，订单号: {}", orderNo);
                return Result.success("处理成功", true);
            } else {
                return Result.fail("处理失败，订单不存在或状态异常");
            }
        } catch (Exception e) {
            log.error("处理支付失败回调失败，订单号: {}", orderNo, e);
            return Result.fail("处理失败：" + e.getMessage());
        }
    }

    // ========================= 退款管理接口 =========================

    /**
     * 申请退款
     * 
     * @param id 支付ID
     * @param refundAmount 退款金额
     * @param refundReason 退款原因
     * @return 退款结果
     */
    @PostMapping("/{id}/refund")
    @Operation(summary = "申请退款", description = "申请支付订单退款")
    public Result<Boolean> applyRefund(
            @Parameter(description = "支付ID") @PathVariable @NotNull Long id,
            @Parameter(description = "退款金额") @RequestParam @NotNull BigDecimal refundAmount,
            @Parameter(description = "退款原因") @RequestParam @NotNull String refundReason) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("申请退款，支付ID: {}, 退款金额: {}, 退款原因: {}, 用户ID: {}", 
                id, refundAmount, refundReason, currentUserId);
            
            // 验证退款参数
            if (refundAmount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.fail("退款金额必须大于0");
            }
            
            boolean success = paymentService.applyRefund(id, refundAmount, refundReason);
            if (success) {
                log.info("申请退款成功，支付ID: {}", id);
                return Result.success("申请成功", true);
            } else {
                return Result.fail("申请失败，支付记录不存在或无权限");
            }
        } catch (Exception e) {
            log.error("申请退款失败，支付ID: {}", id, e);
            return Result.fail("申请失败：" + e.getMessage());
        }
    }

    /**
     * 处理退款成功回调
     * 
     * @param orderNo 订单号
     * @param refundOrderNo 退款订单号
     * @return 处理结果
     */
    @PostMapping("/refund/success")
    @Operation(summary = "处理退款成功回调", description = "处理第三方退款成功回调")
    public Result<Boolean> handleRefundSuccess(
            @Parameter(description = "订单号") @RequestParam @NotNull String orderNo,
            @Parameter(description = "退款订单号") @RequestParam @NotNull String refundOrderNo) {
        try {
            log.info("处理退款成功回调，订单号: {}, 退款订单号: {}", orderNo, refundOrderNo);
            
            boolean success = paymentService.handleRefundSuccess(orderNo, refundOrderNo);
            if (success) {
                log.info("处理退款成功回调成功，订单号: {}", orderNo);
                return Result.success("处理成功", true);
            } else {
                return Result.fail("处理失败，订单不存在或状态异常");
            }
        } catch (Exception e) {
            log.error("处理退款成功回调失败，订单号: {}", orderNo, e);
            return Result.fail("处理失败：" + e.getMessage());
        }
    }

    /**
     * 处理退款失败回调
     * 
     * @param orderNo 订单号
     * @param failureReason 失败原因
     * @return 处理结果
     */
    @PostMapping("/refund/failure")
    @Operation(summary = "处理退款失败回调", description = "处理第三方退款失败回调")
    public Result<Boolean> handleRefundFailure(
            @Parameter(description = "订单号") @RequestParam @NotNull String orderNo,
            @Parameter(description = "失败原因") @RequestParam @NotNull String failureReason) {
        try {
            log.info("处理退款失败回调，订单号: {}, 失败原因: {}", orderNo, failureReason);
            
            boolean success = paymentService.handleRefundFailure(orderNo, failureReason);
            if (success) {
                log.info("处理退款失败回调成功，订单号: {}", orderNo);
                return Result.success("处理成功", true);
            } else {
                return Result.fail("处理失败，订单不存在或状态异常");
            }
        } catch (Exception e) {
            log.error("处理退款失败回调失败，订单号: {}", orderNo, e);
            return Result.fail("处理失败：" + e.getMessage());
        }
    }

    // ========================= 统计查询接口 =========================

    /**
     * 获取支付统计概览
     * 
     * @param communityId 社区ID
     * @return 统计概览
     */
    @GetMapping("/overview/{communityId}")
    @Operation(summary = "获取支付统计概览", description = "获取指定社区的支付统计概览")
    public Result<Map<String, Object>> getPaymentOverview(
            @Parameter(description = "社区ID") @PathVariable @NotNull Long communityId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("获取支付统计概览，社区ID: {}, 用户ID: {}", communityId, currentUserId);
            
            Map<String, Object> overview = paymentService.getPaymentOverview(communityId);
            log.info("获取支付统计概览成功，社区ID: {}", communityId);
            return Result.success("查询成功", overview);
        } catch (Exception e) {
            log.error("获取支付统计概览失败，社区ID: {}", communityId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 统计用户支付总额
     * 
     * @param userId 用户ID
     * @return 支付总额
     */
    @GetMapping("/statistics/user/{userId}")
    @Operation(summary = "统计用户支付总额", description = "统计指定用户的支付总额")
    public Result<BigDecimal> sumAmountByUserId(
            @Parameter(description = "用户ID") @PathVariable @NotNull Long userId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("统计用户支付总额，用户ID: {}, 当前用户ID: {}", userId, currentUserId);
            
            BigDecimal amount = paymentService.sumAmountByUserId(userId);
            log.info("统计用户支付总额成功，用户ID: {}, 总额: {}", userId, amount);
            return Result.success("统计成功", amount);
        } catch (Exception e) {
            log.error("统计用户支付总额失败，用户ID: {}", userId, e);
            return Result.fail("统计失败：" + e.getMessage());
        }
    }

    /**
     * 统计社区支付总额
     * 
     * @param communityId 社区ID
     * @return 支付总额
     */
    @GetMapping("/statistics/community/{communityId}")
    @Operation(summary = "统计社区支付总额", description = "统计指定社区的支付总额")
    public Result<BigDecimal> sumAmountByCommunityId(
            @Parameter(description = "社区ID") @PathVariable @NotNull Long communityId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("统计社区支付总额，社区ID: {}, 用户ID: {}", communityId, currentUserId);
            
            BigDecimal amount = paymentService.sumAmountByCommunityId(communityId);
            log.info("统计社区支付总额成功，社区ID: {}, 总额: {}", communityId, amount);
            return Result.success("统计成功", amount);
        } catch (Exception e) {
            log.error("统计社区支付总额失败，社区ID: {}", communityId, e);
            return Result.fail("统计失败：" + e.getMessage());
        }
    }

    /**
     * 统计各支付方式的支付金额
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 统计结果
     */
    @GetMapping("/statistics/method")
    @Operation(summary = "统计各支付方式的支付金额", description = "统计指定时间范围内各支付方式的支付金额")
    public Result<List<Map<String, Object>>> sumAmountByPaymentMethod(
            @Parameter(description = "开始时间") @RequestParam @NotNull LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam @NotNull LocalDateTime endTime) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("统计各支付方式的支付金额，开始时间: {}, 结束时间: {}, 用户ID: {}", 
                startTime, endTime, currentUserId);
            
            List<Map<String, Object>> statistics = paymentService.sumAmountByPaymentMethod(startTime, endTime);
            log.info("统计各支付方式的支付金额成功，统计项数: {}", statistics.size());
            return Result.success("统计成功", statistics);
        } catch (Exception e) {
            log.error("统计各支付方式的支付金额失败", e);
            return Result.fail("统计失败：" + e.getMessage());
        }
    }

    /**
     * 统计各业务类型的支付金额
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 统计结果
     */
    @GetMapping("/statistics/business")
    @Operation(summary = "统计各业务类型的支付金额", description = "统计指定时间范围内各业务类型的支付金额")
    public Result<List<Map<String, Object>>> sumAmountByBusinessType(
            @Parameter(description = "开始时间") @RequestParam @NotNull LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam @NotNull LocalDateTime endTime) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("统计各业务类型的支付金额，开始时间: {}, 结束时间: {}, 用户ID: {}", 
                startTime, endTime, currentUserId);
            
            List<Map<String, Object>> statistics = paymentService.sumAmountByBusinessType(startTime, endTime);
            log.info("统计各业务类型的支付金额成功，统计项数: {}", statistics.size());
            return Result.success("统计成功", statistics);
        } catch (Exception e) {
            log.error("统计各业务类型的支付金额失败", e);
            return Result.fail("统计失败：" + e.getMessage());
        }
    }

    /**
     * 统计各支付状态的记录数
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 统计结果
     */
    @GetMapping("/statistics/status")
    @Operation(summary = "统计各支付状态的记录数", description = "统计指定时间范围内各支付状态的记录数")
    public Result<List<Map<String, Object>>> countByPaymentStatus(
            @Parameter(description = "开始时间") @RequestParam @NotNull LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam @NotNull LocalDateTime endTime) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("统计各支付状态的记录数，开始时间: {}, 结束时间: {}, 用户ID: {}", 
                startTime, endTime, currentUserId);
            
            List<Map<String, Object>> statistics = paymentService.countByPaymentStatus(startTime, endTime);
            log.info("统计各支付状态的记录数成功，统计项数: {}", statistics.size());
            return Result.success("统计成功", statistics);
        } catch (Exception e) {
            log.error("统计各支付状态的记录数失败", e);
            return Result.fail("统计失败：" + e.getMessage());
        }
    }

    /**
     * 获取每日支付金额趋势
     * 
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 趋势数据
     */
    @GetMapping("/trend/daily")
    @Operation(summary = "获取每日支付金额趋势", description = "获取指定时间范围内的每日支付金额趋势")
    public Result<List<Map<String, Object>>> getDailyPaymentTrend(
            @Parameter(description = "开始日期") @RequestParam @NotNull LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam @NotNull LocalDateTime endDate) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("获取每日支付金额趋势，开始日期: {}, 结束日期: {}, 用户ID: {}", 
                startDate, endDate, currentUserId);
            
            List<Map<String, Object>> trend = paymentService.getDailyPaymentTrend(startDate, endDate);
            log.info("获取每日支付金额趋势成功，数据点数: {}", trend.size());
            return Result.success("查询成功", trend);
        } catch (Exception e) {
            log.error("获取每日支付金额趋势失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取每月支付金额趋势
     * 
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 趋势数据
     */
    @GetMapping("/trend/monthly")
    @Operation(summary = "获取每月支付金额趋势", description = "获取指定时间范围内的每月支付金额趋势")
    public Result<List<Map<String, Object>>> getMonthlyPaymentTrend(
            @Parameter(description = "开始日期") @RequestParam @NotNull LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam @NotNull LocalDateTime endDate) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("获取每月支付金额趋势，开始日期: {}, 结束日期: {}, 用户ID: {}", 
                startDate, endDate, currentUserId);
            
            List<Map<String, Object>> trend = paymentService.getMonthlyPaymentTrend(startDate, endDate);
            log.info("获取每月支付金额趋势成功，数据点数: {}", trend.size());
            return Result.success("查询成功", trend);
        } catch (Exception e) {
            log.error("获取每月支付金额趋势失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    // ========================= 数据导出接口 =========================

    /**
     * 导出支付数据
     * 
     * @param paymentDTO 导出条件
     * @return 导出结果
     */
    @PostMapping("/export")
    @Operation(summary = "导出支付数据", description = "根据条件导出支付数据")
    public Result<String> exportPayments(@Valid @RequestBody PaymentDTO paymentDTO) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("导出支付数据，用户ID: {}, 社区ID: {}, 当前用户ID: {}", 
                paymentDTO.getUserId(), paymentDTO.getCommunityId(), currentUserId);
            
            String result = paymentService.exportPayments(paymentDTO);
            log.info("导出支付数据成功，文件路径: {}", result);
            return Result.success("导出成功", result);
        } catch (Exception e) {
            log.error("导出支付数据失败", e);
            return Result.fail("导出失败：" + e.getMessage());
        }
    }

    /**
     * 导出统计报表
     * 
     * @param communityId 社区ID
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 导出结果
     */
    @GetMapping("/export/statistics")
    @Operation(summary = "导出统计报表", description = "导出支付统计报表")
    public Result<String> exportStatisticsReport(
            @Parameter(description = "社区ID") @RequestParam @NotNull Long communityId,
            @Parameter(description = "开始日期") @RequestParam @NotNull LocalDateTime startDate,
            @Parameter(description = "结束日期") @RequestParam @NotNull LocalDateTime endDate) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("导出统计报表，社区ID: {}, 开始日期: {}, 结束日期: {}, 用户ID: {}", 
                communityId, startDate, endDate, currentUserId);
            
            String result = paymentService.exportStatisticsReport(communityId, startDate, endDate);
            log.info("导出统计报表成功，文件路径: {}", result);
            return Result.success("导出成功", result);
        } catch (Exception e) {
            log.error("导出统计报表失败", e);
            return Result.fail("导出失败：" + e.getMessage());
        }
    }

    // ========================= 缓存管理接口 =========================

    /**
     * 清除支付缓存
     * 
     * @param communityId 社区ID
     * @return 清除结果
     */
    @DeleteMapping("/cache/{communityId}")
    @Operation(summary = "清除支付缓存", description = "清除指定社区的支付缓存")
    public Result<Void> clearPaymentCache(
            @Parameter(description = "社区ID") @PathVariable @NotNull Long communityId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("清除支付缓存，社区ID: {}, 用户ID: {}", communityId, currentUserId);
            
            paymentService.clearPaymentCache(communityId);
            log.info("清除支付缓存成功，社区ID: {}", communityId);
            return Result.success();
        } catch (Exception e) {
            log.error("清除支付缓存失败，社区ID: {}", communityId, e);
            return Result.fail("清除失败：" + e.getMessage());
        }
    }

    /**
     * 清除用户支付缓存
     * 
     * @param userId 用户ID
     * @return 清除结果
     */
    @DeleteMapping("/cache/user/{userId}")
    @Operation(summary = "清除用户支付缓存", description = "清除指定用户的支付缓存")
    public Result<Void> clearUserPaymentCache(
            @Parameter(description = "用户ID") @PathVariable @NotNull Long userId) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("清除用户支付缓存，用户ID: {}, 当前用户ID: {}", userId, currentUserId);
            
            paymentService.clearUserPaymentCache(userId);
            log.info("清除用户支付缓存成功，用户ID: {}", userId);
            return Result.success();
        } catch (Exception e) {
            log.error("清除用户支付缓存失败，用户ID: {}", userId, e);
            return Result.fail("清除失败：" + e.getMessage());
        }
    }

    /**
     * 清除过期支付记录
     * 
     * @param expireTime 过期时间
     * @return 清除数量
     */
    @DeleteMapping("/expired")
    @Operation(summary = "清除过期支付记录", description = "清除过期的支付记录")
    public Result<Integer> clearExpiredPayments(
            @Parameter(description = "过期时间") @RequestParam @NotNull LocalDateTime expireTime) {
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            log.info("清除过期支付记录，过期时间: {}, 用户ID: {}", expireTime, currentUserId);
            
            int count = paymentService.clearExpiredPayments(expireTime);
            log.info("清除过期支付记录成功，清除数量: {}", count);
            return Result.success("清除成功", count);
        } catch (Exception e) {
            log.error("清除过期支付记录失败", e);
            return Result.fail("清除失败：" + e.getMessage());
        }
    }
}
